<?php

namespace app\api\controller;

use app\admin\model\GiftList;
use app\admin\model\MiningCoin;
use app\admin\model\MiningUserWallet;
use app\admin\model\UserLevel;
use app\admin\model\UserMiner;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Config;
use fast\Random;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $data['mobile'] = empty($this->auth->getUser()->mobile) ? $this->auth->getUser()->email : $this->auth->getUser()->mobile ;
        $data['id'] = $this->auth->getUser()->id;
        $data['cal'] = UserMiner::where('user_id',$this->auth->getUser()->id)
            ->where('status','<>',2)->sum('number');

        $data['ipfs'] = UserMiner::where('user_id',$this->auth->getUser()->id)
            ->where('status','<>',2)->where('ktype','<>',2)->where('ktype','<>',4)->sum('number');

        $data['bzz'] = UserMiner::where('user_id',$this->auth->getUser()->id)
            ->where('status','<>',2)->where('ktype',2)->sum('number');

        $data['kd'] = UserMiner::where('user_id',$this->auth->getUser()->id)
            ->where('status','<>',2)->where('ktype',4)->sum('number');

        $data['invitecode'] = $this->auth->getUser()->invitecode;
        $data['level'] = UserLevel::where('id',$this->auth->getUser()->level)->value('name') ?? '普通用户';
        $data['gift'] = GiftList::where('user_id',$this->auth->getUser()->id)
            ->where('status',0)->sum('balance');
        $this->success('ok', $data);
    }

    /**
     * 会员登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 我的团队
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function team()
    {
        $pids = \app\common\model\User::where('pid',$this->auth->getUser()->id)->column('id');
        $data['direct_push'] = count($pids);
        $data['direct_cal'] = UserMiner::whereIn('user_id',$pids)->sum('number');
        $child_ids = getChildsIds($this->auth->getUser()->id);
        $data['team'] = count($child_ids);
        $data['team_cal'] = UserMiner::whereIn('user_id',$child_ids)->sum('number');
        $data['data'] = \app\common\model\User::field('nickname,id,mobile')->where('pid',$this->auth->getUser()->id)->select();
        foreach ($data['data'] as $value) {

            $value->mobile = substr_replace($value->mobile, '****', 3,4);
            $value->cal = UserMiner::where('user_id',$value->id)->sum('number');
        }

        $this->success('ok',$data);
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
//    public function mobilelogin()
//    {
//        $mobile = $this->request->request('mobile');
//        $captcha = $this->request->request('captcha');
//        if (!$mobile || !$captcha) {
//            $this->error(__('Invalid parameters'));
//        }
//        if (!Validate::regex($mobile, "^1\d{10}$")) {
//            $this->error(__('Mobile is incorrect'));
//        }
//        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
//            $this->error(__('Captcha is incorrect'));
//        }
//        $user = \app\common\model\User::getByMobile($mobile);
//        if ($user) {
//            if ($user->status != 'normal') {
//                $this->error(__('Account is locked'));
//            }
//            //如果已经有账号则直接登录
//            $ret = $this->auth->direct($user->id);
//        } else {
//            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
//        }
//        if ($ret) {
//            Sms::flush($mobile, 'mobilelogin');
//            $data = ['userinfo' => $this->auth->getUserinfo()];
//            $this->success(__('Logged in successful'), $data);
//        } else {
//            $this->error($this->auth->getError());
//        }
//    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code   验证码
     */
    public function register()
    {
//        $this->error(   "暂停注册中");
        $account = $this->request->request('account');
        $email = $username = $mobile = '';
//        $email = $this->request->request('email');
//        $mobile = $this->request->request('mobile');
        $password = $this->request->request('password');
        $deal_password = $this->request->request('deal_password');

        if (!$password  || !$deal_password) {
            $this->error(__('Invalid parameters'));
        }
        if (strlen($password) < 6) {
            $this->error(__('Password length cannot be less than').' 6');
        }
        if (strlen($deal_password) < 6) {
            $this->error(__('Transaction password length cannot be less than').' 6');
        }
        $captcha = trim($this->request->request('captcha'));
        if (Validate::regex($account, "^1\d{10}$")) {
//            if (!getConfigValue('sms_register')) {
//                $this->error(__('Operation failed'));
//            }
            $mobile = $username = $account;
            $captcha_check = Sms::check($account, $captcha, 'register');
        } elseif (Validate::is($account, "email")) {
//            if (!getConfigValue('ems_register')) {
//                $this->error(__('Operation failed'));
//            }
            $email = $username = $account;
            $captcha_check = Ems::check($account, $captcha, 'register');
        } else {
            $this->error(__('Account is incorrect'));
        }
//        if ($mobile) {
//            $username = $mobile;
//            if (!getConfigValue('sms_register') || !Validate::regex($mobile, "^1\d{10}$")) {
//                $this->error(__('Mobile is incorrect'));
//            }
//            $captcha_check = Sms::check($mobile, $captcha, 'register');
//        } else {
//            $username = $email;
//            if (!getConfigValue('ems_register') || !Validate::is($email, "email")) {
//                $this->error(__('Email is incorrect'));
//            }
//            $captcha_check = Ems::check($email, $captcha, 'register');
//        }
        if (!$captcha_check) {
            $this->error(__('Captcha is incorrect'));
        }

        //邀请人
        $invitecode = $this->request->post('invitecode');
        $pid = \app\common\model\User::where("invitecode", $invitecode)->value('id') ?? 0;
        if (empty($pid) && !empty(\app\common\model\User::find())) {
            $this->error(__('Recommender does not exist'));
        }
        //邀请码

        $exist = true;
        while ($exist) {
            $invitecode = Random::alnum(5);
            $exist = \app\common\model\User::where('invitecode', $invitecode)->find();
        }
        $path = \app\common\model\User::where('id',$pid)->value('path');
        $path = '-'.$pid.$path;

        $extend = ['path'=>$path, 'invitecode' => $invitecode, 'pid' => $pid, 'deal_password' => $deal_password];
        $ret = $this->auth->register($username, $password, $email, $mobile, $extend);
        if ($ret) {

            $gift_day = Config::where('name','gift_day')->value('value');
            $gift_limit = Config::where('name','gift_limit')->value('value');

            $exist = GiftList::where('user_id',$this->auth->getUser()->id)->find();
            if (empty($exist)) {
                GiftList::create([
                    'user_id' => $this->auth->getUser()->id,
                    'number' =>$gift_limit,
                    'balance' => $gift_limit,
                    'end_time' => date('Y-m-d',strtotime("+$gift_day day"))
                ]);
            }
            $exist = GiftList::where('user_id',$pid)->where('detail_id',$this->auth->getUser()->id)->find();
            if (empty($exist)) {
                GiftList::create([
                    'detail_id' => $this->auth->getUser()->id,
                    'user_id' => $pid,
                    'number' =>$gift_limit,
                    'balance' => $gift_limit,
                    'end_time' => date('Y-m-d',strtotime("+$gift_day day"))
                ]);
            }
            $MiningType = MiningCoin::select();
            foreach ($MiningType as $value) {
                MiningUserWallet::create([
                    'user_id' => $this->auth->getUser()->id,
                    'mining_coin_id' => $value->id,
                    'mining_coin_str' => $value->coin_type
                ]);
            }

            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
//    public function profile()
//    {
//        $user = $this->auth->getUser();
//        $username = $this->request->request('username');
//        $nickname = $this->request->request('nickname');
//        $bio = $this->request->request('bio');
//        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
//        if ($username) {
//            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
//            if ($exists) {
//                $this->error(__('Username already exists'));
//            }
//            $user->username = $username;
//        }
//        $user->nickname = $nickname;
//        $user->bio = $bio;
//        $user->avatar = $avatar;
//        $user->save();
//        $this->success();
//    }

    /**
     * 修改邮箱
     *
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
//    public function changeemail()
//    {
//        $user = $this->auth->getUser();
//        $email = $this->request->post('email');
//        $captcha = $this->request->request('captcha');
//        if (!$email || !$captcha) {
//            $this->error(__('Invalid parameters'));
//        }
//        if (!Validate::is($email, "email")) {
//            $this->error(__('Email is incorrect'));
//        }
//        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
//            $this->error(__('Email already exists'));
//        }
//        $result = Ems::check($email, $captcha, 'changeemail');
//        if (!$result) {
//            $this->error(__('Captcha is incorrect'));
//        }
//        $verification = $user->verification;
//        $verification->email = 1;
//        $user->verification = $verification;
//        $user->email = $email;
//        $user->save();
//
//        Ems::flush($email, 'changeemail');
//        $this->success();
//    }

    /**
     * 修改手机号
     *
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
//    public function changemobile()
//    {
//        $user = $this->auth->getUser();
//        $mobile = $this->request->request('mobile');
//        $captcha = $this->request->request('captcha');
//        if (!$mobile || !$captcha) {
//            $this->error(__('Invalid parameters'));
//        }
//        if (!Validate::regex($mobile, "^1\d{10}$")) {
//            $this->error(__('Mobile is incorrect'));
//        }
//        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
//            $this->error(__('Mobile already exists'));
//        }
//        $result = Sms::check($mobile, $captcha, 'changemobile');
//        if (!$result) {
//            $this->error(__('Captcha is incorrect'));
//        }
//        $verification = $user->verification;
//        $verification->mobile = 1;
//        $user->verification = $verification;
//        $user->mobile = $mobile;
//        $user->save();
//
//        Sms::flush($mobile, 'changemobile');
//        $this->success();
//    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
//    public function third()
//    {
//        $url = url('user/index');
//        $platform = $this->request->request("platform");
//        $code = $this->request->request("code");
//        $config = get_addon_config('third');
//        if (!$config || !isset($config[$platform])) {
//            $this->error(__('Invalid parameters'));
//        }
//        $app = new \addons\third\library\Application($config);
//        //通过code换access_token和绑定会员
//        $result = $app->{$platform}->getUserInfo(['code' => $code]);
//        if ($result) {
//            $loginret = \addons\third\library\Service::connect($platform, $result);
//            if ($loginret) {
//                $data = [
//                    'userinfo'  => $this->auth->getUserinfo(),
//                    'thirdinfo' => $result
//                ];
//                $this->success(__('Logged in successful'), $data);
//            }
//        }
//        $this->error(__('Operation failed'), $url);
//    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->request("type");
        $account = $this->request->request('account');
//        $mobile = $this->request->request("mobile");
//        $email = $this->request->request("email");
        $new_password = $this->request->request("new_password");
        if (!$new_password) {
            $this->error(__('Invalid parameters'));
        }

        if (strlen($new_password) < 6) {
            $this->error(__('Password length cannot be less than').' 6');
        }

        if ($type == 'user') {
            $old_password = $this->request->request("old_password");
            $user = $this->auth->getUser();
            $ret = $this->auth->changepwd($new_password, $old_password, false);
            if (!$ret) {
                $this->error($this->auth->getError());
            }
        } else {
            $captcha = $this->request->request("captcha");
            if (Validate::regex($account, "^1\d{10}$")) {
                if (!getConfigValue('sms_register')) {
                    $this->error(__('Operation failed'));
                }
                $user = \app\common\model\User::getByMobile($account);
                if (!$user) {
                    $this->error(__('User not found'));
                }
                $ret = Sms::check($account, $captcha, 'resetpwd');
                if (!$ret) {
                    $this->error(__('Captcha is incorrect'));
                }
                Sms::flush($account, 'resetpwd');
            } elseif (Validate::is($account, "email")) {
                if (!getConfigValue('ems_register')) {
                    $this->error(__('Operation failed'));
                }
                $user = \app\common\model\User::getByEmail($account);
                if (!$user) {
                    $this->error(__('User not found'));
                }
                $ret = Ems::check($account, $captcha, 'resetpwd');
                if (!$ret) {
                    $this->error(__('Captcha is incorrect'));
                }
                Ems::flush($account, 'resetpwd');
            } else {
                $this->error(__('Account is incorrect'));
            }
        }

        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($new_password, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 重置交易密码
     */
    public function resetDealpwd()
    {
        $type = $this->request->request("type");
        if ($this->request->post()) {
            $captcha = $this->request->post('captcha');
            $new_dealpassword = $this->request->post("new_dealpassword");
            if (!$new_dealpassword) {
                $this->error(__('Invalid parameters'));
            }
            if (strlen($new_dealpassword) < 6) {
                $this->error(__('Deal password length cannot be less than'). ' 6');
            }

            if ($type == 'user') {
                $deal_password = $this->request->post('old_dealpassword');
                if ($deal_password != $this->auth->getUser()->deal_password) {
                    $this->error(__('Transaction password is incorrect'));
                }
            } else {
                if ($type == 'email') {
                    $account = $this->auth->getUser()->email;
                    $captcha_check = Ems::check($account, $captcha, 'resetdealpasswd');

                } else {
                    $account = $this->auth->getUser()->mobile;
                    $captcha_check = Sms::check($account, $captcha, 'resetdealpasswd');
                }
                if (!$captcha_check) {
                    $this->error(__('Captcha is incorrect'));
                }
            }
            \app\common\model\User::where('id',$mobile = $this->auth->getUser()->id)
                ->update(['deal_password' => $new_dealpassword]);
            $this->success(__('Alter successful'));
        } else {
            $data['email'] =$this->auth->getUser()->email;
            $data['mobile'] = $this->auth->getUser()->mobile;
            $this->success($data);
        }
    }

}
